<?php
namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class Company extends Controller
{
    use \App\Traits\UserTrait, \App\Traits\AjaxTrait, \App\Traits\CompanyTrait, \App\Traits\CacheTrait, \App\Traits\ApiTrait, \App\Traits\DbTrait, \App\Traits\SessionTrait, \App\Traits\ErrorTrait;

    public function addCompanyInfo()
    {
        if ($this->sessionReturnCompanyId() && !$this->sessionReturnUserCECIFF()) {
            return redirect('/user/company');
        }
        $viewData = [
            'seo' => ['title' => '', 'key_word' => '', 'desc' => ''],
        ];
        return view('web.company.main', $viewData);
    }

    public function firstStep()
    {
        $viewData = [
            'seo' => ['title' => '', 'key_word' => '', 'desc' => ''],
        ];
        return view('web.company.first_step', $viewData);
    }

    public function showAddInfo()
    {
        $viewData = [
            'seo' => ['title' => '', 'key_word' => '', 'desc' => ''],
            'provinceList' => $this->cacheGetProvinceList(),
        ];
        return view('web.company.add', $viewData);
    }

    public function domainPage()
    {
        $otherDicList = $this->cacheGetOtherDicList();
        $domainList = $otherDicList['LYZD'];
        $viewData = [
            'firstDomainList' => $domainList[0],
            'domainList' => $domainList,
        ];
        return view('web.company.domain_page', $viewData);
    }

    public function getTechDomainInfo(Request $request)
    {
        $domainStr = $request->input('domain');
        $domainData = trim($domainStr, ',');
        $result = $this->domainGetTechRoute(parent::CODE_GET_DOMAIN_TECHROUTE_LIST, $domainData);
        echo $result ? json_encode(['result' => 0]) : json_encode(['result' => -1]);
    }

    public function techPathPage(Request $request)
    {
        $domainStr = $request->input('domain');
        if ($domainStr) {
            $domainData = trim($domainStr, ',');
            $result = $this->domainGetTechRoute(parent::CODE_GET_DOMAIN_TECHROUTE_LIST, $domainData);
            //$otherDicList = $this->cacheGetOtherDicList();
            //$techRouteList = $otherDicList['JSLJ'];
            $viewData = [
                //'firstTechRouteList' => $techRouteList[0],
                'techRouteList' => $result,
            ];
            return view('web.company.tech_path', $viewData);
        } else {
            abort(404);
        }

    }

    /**
     * 提交公司信息
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function postCompanyInfo(Request $request)
    {
        $postData = $this->ajaxCompanyAddInfo($request);
        $postData['company_id'] = $this->sessionReturnCompanyId();
        $postData['account_phone'] = $this->sessionReturnUserPhone();
        $result = $this->authCompanyServicerInfoFromFront(parent::CODE_AUTH_COMPANY_OWNER_SERVICER_INFO, $postData);
        if ($result === true) {
            $mailInfo = [
                'mail_address' => $request->input('email'),
                'mail_subject' => '碳银网信息提交邮箱认证',
                'mail_content' => '请确认邮件，并且进行激活。点击<a href="#URL_HERE#">邮件激活</a>进行激活',
            ];

            $insertData = [
                'phone' => $postData['account_phone'],
                'email' => $mailInfo['mail_address'],
            ];
            $insertData['md5'] = $this->createEmailAuthCode($insertData['phone'], $insertData['email'], time());
            $dbResult = $this->addEmailValidateInfo($insertData);

            $mailInfo['mail_content'] = str_replace('#URL_HERE#', env('EMAIL_VALIDATE_URL') . '?flag=' . $insertData['md5'] . '&source=' . $mailInfo['mail_address'], $mailInfo['mail_content']);

            $result = $this->pushEmailData(parent::CODE_SEND_EMAIL, $mailInfo);
            echo $result ? json_encode($this->emailPushSuccess()) : json_encode($this->emailPushFail());
        } elseif ($result['succ'] == -3) {
            echo json_encode($this->companyNameSameError());
        } else {
            echo json_encode($this->normalError());
        }
    }

    public function companyNameAuth(Request $request)
    {
        $data = [
            'companyName' => $request->input('companyName'),
        ];
        $result = $this->authCompanyNameInfo(parent::CODE_AUTH_COMPANY_NAME, $data);
        if ($result) {
            echo json_encode(['result' => 1, 'company_id' => $result, 'msg' => '公司名称已存在']);
        } else {
            echo json_encode(['result' => 0]);
        }
    }

    public function companyInfo(Request $request)
    {
        $data = [
            'company_id' => $request->input('id'),
        ];
        $result = $this->getCompanyInfo(parent::CODE_GET_COMPANY_INFO, $data);
        if ($result) {
            if ($result['company_regist_address_id']) {
                list($p, $c, $a) = explode(',', $result['company_regist_address_id']);
                $pName = $this->cacheFromAreaIdGetName($p);
                $cName = $this->cacheFromAreaIdGetName($c);
                $aName = $this->cacheFromAreaIdGetName($a);
            } else {
                $pName = $cName = $aName = '';
            }
            $arrDomain2 = [];
            $arrCacheDicNameList = $this->cacheGetOtherDicNameList();
            if (trim($result['company_domain_id'], ',')) {
                $arrDomain = explode(',', trim($result['company_domain_id']));
                for ($i = 0; $i < count($arrDomain); $i++) {
                    $arrDomain2[] = $arrCacheDicNameList[$arrDomain[$i]]['name'];
                }
            }
            $techRouteInfo = [];
            if (json_decode($result['tech_route_info'])) {
                $arrTechRoute = json_decode($result['tech_route_info'], true);
                for ($i = 0; $i < count($arrTechRoute); $i++) {
                    $techRouteInfo[$i]['name'] = $arrCacheDicNameList[$arrTechRoute[$i]['id']]['name'];
                    $techRouteInfo[$i]['flag'] = decbin($arrTechRoute[$i]['ab']);
                }
            }
            $viewData = [
                'seo' => $this->returnSeoInfo('tanwin_index'),
                'companyName' => $result['company_name'],
                'registAddressNameP' => $pName,
                'registAddressNameC' => $cName,
                'registAddressNameA' => $aName,
                'registAddress' => $result['company_regist_address'],
                'leganUser' => $result['legan_user_name'],
                'domain' => $arrDomain2,
                'techRouteInfo' => $techRouteInfo,
            ];
            return view('web.company.info', $viewData);
        } else {
            abort(404);
        }
    }
}
